package com.tornado.community.controller;

import com.tornado.community.dto.AccessTokenDto;
import com.tornado.community.dto.GitHubUser;
import com.tornado.community.mapper.custome.MyUserMapper;
import com.tornado.community.model.User;
import com.tornado.community.provider.GitHubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@Controller
public class AuthorizeController {

    private final GitHubProvider gitHubProvider;
    private final MyUserMapper myUserMapper;

    @Autowired
    public AuthorizeController(GitHubProvider gitHubProvider, MyUserMapper myUserMapper) {
        this.gitHubProvider = gitHubProvider;
        this.myUserMapper = myUserMapper;
    }

    @Value("${gitHub.client.id}")
    private String clientId;
    @Value("${gitHub.client.secret}")
    private String clientSecret;
    @Value("${gitHub.client.redirect}")
    private String clientRedirect;


    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response) throws IOException {
        //使用code从GitHub获取用户信息
        AccessTokenDto accessTokenDto = new AccessTokenDto();
        accessTokenDto.setClient_id(clientId);
        accessTokenDto.setClient_secret(clientSecret);
        accessTokenDto.setCode(code);
        accessTokenDto.setRedirect_uri(clientRedirect);
        accessTokenDto.setState(state);
        String accessToken = gitHubProvider.getAccessToken(accessTokenDto);
        GitHubUser gitHubUser = gitHubProvider.getGitHubUser(accessToken);
        //持久化用户信息
        if (gitHubUser != null && gitHubUser.getId() != null) {
            User user = myUserMapper.selectByAccountId(String.valueOf(gitHubUser.getId()));
            if (user != null) {
                user.setGmtModify(System.currentTimeMillis());
                user.setToken(UUID.randomUUID().toString());
                myUserMapper.updateUser(user);
            } else {
                user = new User();
                user.setAccountId(String.valueOf(gitHubUser.getId()));
                user.setName(gitHubUser.getName());
                user.setToken(UUID.randomUUID().toString());
                user.setGmtCreate(System.currentTimeMillis());
                user.setGmtModify(user.getGmtCreate());
                user.setBio(gitHubUser.getBio());
                user.setAvatarUrl(gitHubUser.getAvatar_url());
                myUserMapper.insertUser(user);
            }
            Cookie token = new Cookie("token", user.getToken());
            token.setMaxAge(3600 * 24 * 7);
            response.addCookie(token);
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session, HttpServletResponse response) {
        session.removeAttribute("user");
        Cookie token = new Cookie("token", null);
        token.setMaxAge(0);
        response.addCookie(token);
        return "redirect:/";
    }

    @GetMapping("/force/login")
    public String forceLogin(HttpServletResponse response, HttpSession session) {
        String uuid = UUID.randomUUID().toString();
        User user = myUserMapper.selectByAccountId("22277254");

        user.setToken(uuid);
        myUserMapper.updateUser(user);
        session.setAttribute("user", user);
        Cookie token = new Cookie("token", uuid);
        token.setPath("/");
        token.setMaxAge(3600 * 24 * 7);
        response.addCookie(token);
        return "redirect:/";
    }
}
